<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="item.tmName" :value="item.id" v-for="item in tradeMarkList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" rows="4" placeholder="描述" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload action="/dev-api/admin/product/fileUpload" 
        list-type="picture-card" 
        :on-preview="handlePictureCardPreview" 
        :on-remove="handleRemove" 
        :on-success="handleSuccess"
        :file-list="spuImageList">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还剩${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :label="item.name" :value="`${item.id}:${item.name}`" v-for="item in unSelectSaleAttr" :key="item.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" style="margin: 0 10px" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性</el-button>
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center"> </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width"> </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small" @blur="handleInputConfirm(row)"> </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row, $index}">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu: {
        // 三级分类的id
        category3Id: '',
        // 描述
        description: '',
        // SPU名称
        spuName: '',
        // 品牌的id
        tmId: '',
        // SPU图片的信息
        spuImageList: [
        ],
        // 平台属性与属性值的收集
        spuSaleAttrList: [
          // {
          //   "baseSaleAttrId": 0,
          //   "id": 0,
          //   "saleAttrName": "string",
          //   "spuId": 0,
          //   "spuSaleAttrValueList": [
          //     {
          //       "baseSaleAttrId": 0,
          //       "id": 0,
          //       "isChecked": "string",
          //       "saleAttrName": "string",
          //       "saleAttrValueName": "string",
          //       "spuId": 0
          //     }
          //   ]
          // }
        ]
      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储SPU图片的数据
      saleAttrList: [], //销售属性的数据
      attrIdAndAttrName: '', //收集未选择的销售属性的id和销售属性
    }
  },
  methods: {
    // 照片墙删除某一图片时会触发
    handleRemove(file, fileList) {
      this.spuImageList = fileList
    },
    // 照片墙图片预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 初始化spuForm数据
    async initSpuForm(row) {
      let spuResult = await this.$API.spu.reqSpu(row.id)
      if (spuResult.code == 200) {
        this.spu = spuResult.data
      }
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList()
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      let spuImageResult = await this.$API.spu.reqSpuImageList(row.id)
      if (spuImageResult.code == 200) {
        let imgData = spuImageResult.data
        imgData.map(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = imgData
      }
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data
      }
    },
    // 照片墙上传成功的回调
    handleSuccess(response, file, fileList) {
      this.spuImageList = fileList
    },
    // 添加新的销售属性
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      let newAttr = {baseSaleAttrId, saleAttrName, spuSaleAttrValueList: []}
      this.spu.spuSaleAttrList.push(newAttr)
      this.attrIdAndAttrName = ''
    },
    // 添加按钮的回调
    addSaleAttrValue(row) {
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'inputValue', '')
    },
    // el-input 失去焦点的回调
    handleInputConfirm(row) {
      const {baseSaleAttrId, inputValue} = row
      if(inputValue.trim() == '') {
        this.$message({type: 'warning', message: '属性值不能为空'})
        this.$refs.saveTagInput.focus()
        return
      }
      let result = row.spuSaleAttrValueList.some(item=>item.saleAttrValueName==inputValue)
        if(result) {
          this.$message({type: 'warning', message: '属性值不能重复'})
          this.$refs.saveTagInput.focus()
          return
        }
      let newSaleAttrValue = {baseSaleAttrId, saleAttrValueName:inputValue}
      row.spuSaleAttrValueList.push(newSaleAttrValue)
      row.inputVisible = false
    },
    // 保存按钮的回调
   async addOrUpdateSpu() {
     this.spu.spuImageList = this.spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl?item.imgUrl:item.response.data
        }
      });
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
      if(result.code==200) {
        this.$message({type: 'success', message: '保存成功'})
        this.$emit('changeScene', {scene: 0, flag:this.spu.id?'修改':'添加'})
      }
      // 清除数据
      Object.assign(this._data, this.$options.data())
    },
   async addSpuData(category3Id) {
    this.spu.category3Id = category3Id
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList()
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data
      }
    },
    cancel() {
      this.$emit('changeScene', {scene: 0, flag: ''})
      // 清除数据
      Object.assign(this._data, this.$options.data())
    }
  },
  computed: {
    // 计算出还未选择的销售属性
    unSelectSaleAttr() {
      let result = this.saleAttrList.filter(item => {
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name != item1.saleAttrName
        })
      })
      return result
    }
  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
